
const DB_PATH = '_doc/media.db'
const DB_NAME = 'media'
const TABLE = 'media'
const DIR = '_doc/media/'

const openDB = () =>{
	return new Promise((resolve, reject) => {
		plus.sqlite.openDatabase({
			name: DB_NAME,
			path: DB_PATH,
			success: resolve,
			fail: reject
		});
	})
}

const isOpen = () =>{
	return plus.sqlite.isOpenDatabase({
		name: DB_NAME,
		path: DB_PATH,
	})
}

const closeDB = () =>{
	return new Promise((resolve, reject) => {
		plus.sqlite.closeDatabase({
			name: JDBC.DB_NAME,
			success: resolve,
			fail: reject
		})
	})
}

const executeSql = async (sql) =>{
	if (!isOpen()) {
		await openDB()
	}
	return new Promise((resolve, reject) => {
		plus.sqlite.executeSql({
			name: DB_NAME,
			sql: sql,
			success: resolve,
			fail: reject
		})
	})
}
const selectSql = async (sql)=>{
	if (!isOpen()) {
		await openDB()
	}
	return new Promise((resolve, reject) => {
		plus.sqlite.selectSql({
			name: DB_NAME,
			sql: sql,
			success: resolve,
			fail: reject
		})
	})	
}

export const createTable = async () =>{
	if(isOpen()){
		await openDB()
	}
	const sql = `CREATE TABLE if not exists ${TABLE}(
			"url" VARCHAR,
			"path" VARCHAR
		)`
	return executeSql(sql)
}

export const pathByUrl = async (url) =>{
	const sql = `SELECT path from ${TABLE} where url = "${url}" LIMIT 1`
	const [{path=''}={}] = await selectSql(sql)
	return path
}

export const addPath=(url,path)=>{
	const sql = `INSERT INTO ${TABLE} (url,path) VALUES ("${url}","${path}")`
	return executeSql(sql)
}

export const updatePath = (url,path)=>{
	const sql = `UPDATE ${TABLE} SET path = "${path}" WHERE url = "${url}"`
	return executeSql(sql)
}

export const clearPath = ()=>{
	const sql = `DELETE FROM ${TABLE}`
	return executeSql(sql)
}

export const removeByPath = (path) =>{
	const sql = `DELETE FROM ${TABLE} WHERE path = "${path}"`
	return executeSql(sql)
}


export const removeByUrl = (url) =>{
	const sql = `DELETE FROM ${TABLE} WHERE url = "${url}"`
	return executeSql(sql)
}

export const downToPath = async (url)=>{
	if(!url){
		return ''
	}
	const path = await new Promise((resolve,reject)=>{
		const task = plus.downloader.createDownload(url,{filename:DIR},(dl,code)=>{
			if(code==200){
				resolve(dl.filename)
			}else{
				reject(new Error(`图片下载失败${url}`))
			}
		})
		task.start()
	})
	await addPath(url,path)
	return path
}

export const copyToPath = async (filePath,url)=>{
	let path = await pathByUrl(url)
	if(!!path){
		return path
	}
	const fileEntry = await new Promise((resolve,reject)=>{
		plus.io.resolveLocalFileSystemURL( filePath, resolve, reject );
	})
	const dirEntry = await new Promise((resolve,reject)=>{
		plus.io.resolveLocalFileSystemURL( DIR, resolve, reject );
	})
	path = await new Promise((resolve,reject)=>{
		dirEntry.getFile(fileEntry.name,{},(entry)=>{
			
			resolve(entry.toURL())
		},()=>{
			
			fileEntry.copyTo(dirEntry,{},(entry)=>{
				resolve(entry.toURL())
			}, reject)
		})
	})
	await addPath(url,path)
	return path
}


export const renewMedium = async (url) =>{
	const old = await pathByUrl(url)
	if(!old){
		return downToPath(url)
	}
	const path = await new Promise((resolve,reject)=>{
		const task = plus.downloader.createDownload(url,{filename:DIR},(dl,code)=>{
			if(code==200){
				resolve(dl.filename)
			}else{
				reject(new Error(`图片下载失败${url}`))
			}
		})
		task.start()
	})
	await updatePath(url,path)
	plus.io.resolveLocalFileSystemURL( old, (entry)=>{
		entry.remove()
	}, (e)=>{
		console.log(e)
	} );
	return path
}

export const queryAll = async ()=>{
	const sql = `SELECT * from ${TABLE}`
	const list = await selectSql(sql)
	return list
}